﻿using Microsoft.Extensions.Configuration;
using MyK3CloudCore.IOC;
using MyK3CloudCore.IOC.DataEntity;
using MyK3CloudCore.IOC.Extensions;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;

namespace Microsoft.Extensions.DependencyInjection;

public static class K3IOCServiceCollectionExtensions
{
    internal static K3Config Configs;
    internal static LoginResult LoginResult;
    internal static readonly CookieContainer _cookie = new();
    internal static IHttpClientFactory HttpClientFactory;
    /// <summary>
    /// K3注入语法糖
    /// </summary>
    public static IServiceCollection AddK3Sugar(this IServiceCollection server, K3Config config)
    {
        Configs = config ?? throw new ArgumentNullException(nameof(K3Config));
        server.AddDefaultHttpClient(_cookie);
        HttpClientFactory = server.BuildServiceProvider().GetService<IHttpClientFactory>();
        return server;
    }
    /// <summary>
    /// lambda 表达式来设置K3Config
    /// </summary>
    public static IServiceCollection AddK3Sugar(this IServiceCollection server, Action<K3Config> setupAction)
    {
        K3Config k3Config = new();
        setupAction?.Invoke(k3Config);
        return AddK3Sugar(server, k3Config);
    }
    /// <summary>
    /// 读取appsettings.json文件K3CLOUDCONFIG节点配置
    /// </summary>
    public static IServiceCollection AddK3Sugar(this IServiceCollection server)
    {
        var builder = new ConfigurationBuilder().AddInMemoryCollection().AddJsonFile("appsettings.json", false).Build();
        var k3CloudConfit = builder.GetSection("K3CLOUDCONFIG");
        if (k3CloudConfit == null) { throw new ArgumentNullException(nameof(k3CloudConfit)); }
        var k3Config = builder.GetValue<K3Config>("K3CLOUDCONFIG");
        if (k3Config == null)
        {
            var children = builder.GetSection("K3CLOUDCONFIG").GetChildren();
            k3Config = children.First().Get<K3Config>();
        }
        return AddK3Sugar(server, k3Config);
    }
}

